package com.ling.controller;

import com.ling.bean.Msg;
import com.ling.bean.User;
import com.ling.service.UserService;
import com.ling.util.SmsZhenZiUtil;
import com.ling.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;

@Controller
public class RegisterController {
    private final UserService userService;

    @Autowired
    public RegisterController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/register")
    public String goToRegister() {
        return "register";
    }

    //发送验证码
    @PostMapping(value = "/sendCode")
    @ResponseBody
    public Msg sendCode(@RequestParam String tel, HttpSession session) {
        if (userService.existTel(tel)) {
            //该手机号已注册，请直接登录
            return Msg.fail().add("error","该手机号已注册，请直接登录");
        } else {
            //该手机号可注册
            //生成随机验证码,并放入session中
            String code = StringUtil.getRandomString(6);
            System.out.println("手机号："+tel+" 短信验证码："+code);
            session.setAttribute("code", code);
            if (SmsZhenZiUtil.sendSMS(tel,code)) {
                //请求成功
                return Msg.success();
            } else {
                //请求失败
                return Msg.fail().add("error","系统繁忙，请稍后重试！！！");
            }
        }
    }

    //注册
    @PostMapping(value = "/register")
    @ResponseBody
    public Msg register(@Valid User user,@RequestParam String code,@Autowired HttpSession session, BindingResult result) {
        //字段验证
        if (result.hasErrors()) {
            return Msg.fail().add("error","表单填写错误，请检查并重新注册！");
        } else {
            //校验成功
            //手机号重复验证
            if (userService.existTel(user.getTel())) {
                //该手机号已注册，请直接登录
                return Msg.fail().add("error","该手机号已注册，请直接登录!");
            } else {
                //该手机号可注册
                //判断验证码
                String correct_code = (String) session.getAttribute("code");
                if(!code.equals(correct_code)){
                    //验证码错误，直接返回
                    return Msg.fail().add("error","验证码错误!");
                }
                //创建userId,followingusernum,jiyan,fannum
                user.setId(StringUtil.getRandomString(16));
                user.setFollowingusernum(0);
                user.setFannum(0);
                user.setJiyan(0);
                //保存用户
                userService.saveUser(user);
                return Msg.success();
            }

        }
    }
}
